#include <stdio.h>

typedef struct student
{
    char name[30];
    char num[20];
    int Chinese;
    int math;
    int English;
}student;

void stu_config(student *stu, int num)
{
    int i = 0;
    
    for(i=0; i<num; i++)
    {
        printf("stu %d name:", i);
        scanf("%s", stu[i].name);
        printf("stu %d num:", i);
        scanf("%s", stu[i].num);
        printf("stu %d Chinese grade:", i);
        scanf("%d", &stu[i].Chinese);
        printf("stu %d math grade:", i);
        scanf("%d", &stu[i].math);
        printf("stu %d English grade:", i);
        scanf("%d", &stu[i].English);

        printf("%s %s %d %d %d\n", stu[i].name,
            stu[i].num, stu[i].Chinese, stu[i].math, stu[i].English);
    }
}

void save_file(FILE * fp, student *arr, int num)
{
    int i = 0;
    for(i=0; i<num; i++)
    {//需要加'\n',因为之前用的scanf都没有读到'\n'
        fprintf(fp, "%s %s %d %d %d\n", arr[i].name,
        arr[i].num, arr[i].Chinese, arr[i].math, arr[i].English);
    }
}

int show_file(FILE *fp)
{
    char buf[100] = {0};
    char *s = buf;
    s = fgets(s, sizeof(buf), fp);
    while(s != NULL)
    {
        printf("[show_file]:%s", s);
        s = fgets(s, sizeof(buf), fp);
    }
    if(feof(fp))
    {
        printf("end of file\n");
        return 0;
    }
    else if(ferror(fp))
    {
        printf("fgets file fail");
        return -1;
    }
}

int main(int argc, char *argv[1])
{
    if(argc != 2)
    {
        printf("please input 2 arguments! such as ./a.out <file>\n");
        return -1;
    }

    int cnt = 0;
    int i = 0;

    FILE *fp = fopen(argv[1], "w+");
    if(fp == NULL)
    {
        perror("fopen fail");
        return -1;
    }

    printf("please input num of student:\n");
    scanf("%d", &cnt);
    student stu[cnt];
    // memset(stu, 0, sizeof(student)*cnt);
    stu_config(stu, cnt);
    save_file(fp, stu, cnt);
    
    // fclose(fp);
    // fp = fopen(argv[1], "w+");
    // if(fp == NULL)
    // {
    //     perror("fopen fail");
    //     return -1;
    // }
    rewind(fp);

    show_file(fp);

    return 0;
}